<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !detailListInfo.visible &&
        !detailInfo.visible &&
        !purchOrderCheckApplicationInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-merge>
            <el-button
              :disabled="!canMerge"
              @click="handelMethodRequest(undefined, 'merge')"
              >合单</el-button
            >
          </template>
          <template v-slot:filter-revoke>
            <el-button
              :disabled="!canRevoke"
              @click="handelMethodRequest(undefined, 'revoke')"
              >撤回</el-button
            >
          </template>
          <template v-slot:filter-ratify>
            <el-button
              :disabled="!canRatify"
              @click="handelMethodRequest(undefined, 'ratify')"
              >批准</el-button
            >
          </template>
          <template v-slot:filter-review>
            <el-button
              :disabled="!canReview"
              @click="handelMethodRequest(undefined, 'review')"
              >复核</el-button
            >
          </template>
          <template v-slot:filter-stop>
            <el-button
              :disabled="!canStop"
              @click="handelMethodRequest(undefined, 'stop')"
              >中止</el-button
            >
          </template>
          <template v-slot:filter-submit>
            <el-button
              :disabled="!canSubmit"
              @click="handelMethodRequest(undefined, 'submit')"
              >提交</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('purchApplication:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else>{{ scope.row.orderNo }}</span>
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <!-- 新增或修改 -->
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      tableKey="purchApplicationOrderList-com.slip.spd.entity.vo.purch.PurchApplicationVO"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <checkPurchApplication
      v-if="purchOrderCheckApplicationInfo.visible"
      v-model:visible="purchOrderCheckApplicationInfo.visible"
      :purch-application-id="purchOrderCheckApplicationInfo.orderId"
      :purch-application-info="purchOrderCheckApplicationInfo.info"
      :purch-type="purchOrderCheckApplicationInfo.purchType"
      :purch-according="purchOrderCheckApplicationInfo.purchAccording"
      :title="purchOrderCheckApplicationInfo.title"
      @returnModify="returnModify"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <page-dialog
      v-if="pageDialogInfo.visible"
      :title="pageDialogInfo.title"
      v-model:visible="pageDialogInfo.visible"
      :width="pageDialogInfo.width"
      :bt-loading="pageDialogInfo.btLoading"
      :bt-list="pageDialogInfo.btList"
      @reset="closeDialog"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="pageFormInfo.ref"
        :data="pageFormInfo.data"
        :field-list="pageFormInfo.fieldList"
        :label-width="pageFormInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>
<script setup name="purchApplication">
import {
  postPurchApplicationPage,
  removePurchApplication,
  methodPurchApplication,
  applicationsValidatePurch,
  applicationsSubmitValidatePlanRemind
} from '@/api/purch'
import { getDeptAll, getReceiveAddressAll } from '@/api/core'
import detail from './detail'
import modify from './modify'
import detailList from './detailList'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

import checkPurchApplication from '@/views/purch/order/checkPurchApplication'

const { proxy } = getCurrentInstance()
const allow_purch_application_approval = computed(() => {
  return proxy.$store.state.permission.systemConfig
    .allow_purch_application_approval == -2
    ? 0
    : proxy.$store.state.permission.systemConfig
        .allow_purch_application_approval
})
const allow_purch_application_re_approval = computed(() => {
  return proxy.$store.state.permission.systemConfig
    .allow_purch_application_re_approval == -2
    ? 0
    : proxy.$store.state.permission.systemConfig
        .allow_purch_application_re_approval
})
const pageDialogInfo = ref({
  title: '选择采购依据',
  visible: false,
  type: '',
  width: '400px',
  row: {},
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveDialog,
      saveLoading: false,
      show: true,
    },
  ],
})
const pageFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购依据',
      value: 'purch_according',
      type: 'select-model',
      code: 'purch_according',
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'purch_application',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      purchProductType: {
        asTbName: 'purch_application',
        columnName: 'purch_product_type',
        queryType: 'EQUALS',
        queryResource: 0,
        queryCategory: 'AND',
        value: '1',
      },
    },
    groupMap: {},
    groups: [],
    queryParams: {},
  },
  searchList: [],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('purchApplication:add'),
    },
    {
      type: 'slot',
      value: 'merge',
      show: proxy.$permission('purchApplication:merge'),
    },
    {
      type: 'slot',
      value: 'revoke',
      show: proxy.$permission('purchApplication:revoke'),
    },
    {
      type: 'slot',
      value: 'ratify',
      show: proxy.$permission('purchApplication:ratify'),
    },
    {
      type: 'slot',
      value: 'review',
      show: proxy.$permission('purchApplication:review'),
    },
    {
      type: 'slot',
      value: 'stop',
      show: proxy.$permission('purchApplication:stop'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('purchApplication:submit'),
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: _search },
    { type: 'button', label: '高级查询', event: _advancedSearchShow },
    { type: 'button', label: '重置', event: _clearSearch },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '删除',
        event: remove,
        show: proxy.$permission('purchApplication:del'),
        popconfirmText: '删除后将改变数据,是否继续？',
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('purchApplication:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: (row) => handelMethodRequest(row, 'submit'),
        show: proxy.$permission('purchApplication:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: (row) => handelMethodRequest(row, 'revoke'),
        show: proxy.$permission('purchApplication:revoke'),
        ifRender: ifRenderRevoke,
      },
      {
        label: '批准',
        event: (row) => handelMethodRequest(row, 'ratify'),
        show: proxy.$permission('purchApplication:ratify'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '复核',
        event: (row) => handelMethodRequest(row, 'review'),
        show: proxy.$permission('purchApplication:review'),
        ifRender: function (row) {
          return row.status === 13
        },
      },
      {
        label: '退回',
        event: (row) => handelMethodRequest(row, 'return'),
        show: proxy.$permission('purchApplication:return'),
        ifRender: function (row) {
          return row.status === 13
        },
      },
      {
        label: '驳回',
        event: (row) => handelMethodRequest(row, 'reject'),
        show: proxy.$permission('purchApplication:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '生成采购单',
        event: handelGeneratePurch,
        show: proxy.$permission('purchApplication:generate'),
        ifRender: function (row) {
          return row.status === 5 || row.status === 3
        },
      },
      {
        label: '拆单',
        event: (row) => handelMethodRequest(row, 'split'),
        show: proxy.$permission('purchApplication:split'),
        ifRender: function (row) {
          return (
            (row.status === 1 ||
              row.status === 2 ||
              row.status === 3 ||
              row.status === 13) &&
            row.mergedOrders.length > 0 &&
            row.status === row.beforeMergeStatus
          )
        },
      },
      {
        label: '中止',
        event: (row) => handelMethodRequest(row, 'stop'),
        show: proxy.$permission('purchApplication:stop'),
        ifRender: ifRenderStop,
      },
    ],
  },
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '申购单明细',
  data: {},
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  orderId: '',
})
const deptSelectInfo = reactive({
  api: getDeptAll,
  query: {
    deptAuth: 'id',
  },
})
const purchOrderCheckApplicationInfo = ref({
  visible: false,
  title: '通过申购单生成采购单',
  purchType: 0,
  orderId: null,
  info: undefined,
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const tableKey =
  'purchApplicationOrderList-com.slip.spd.entity.vo.purch.PurchApplicationVO'
const selectRow = ref({})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
watch(
  () => proxy.$router,
  (route) => {
    if (
      route &&
      route.currentRoute &&
      route.currentRoute.value &&
      route.currentRoute.value.name === 'purchApplication'
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'purchApplication' && el.url === val.url) {
                modifyInfo.visible = false
                detailListInfo.value.visible = false
                advancedSearchInfo.value.visible = false
                preferenceInfo.value.visible = false
                detailInfo.visible = false
                purchOrderCheckApplicationInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  let data = {
                    id: val.businessId,
                  }
                  detailInfo.data = data
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

const canSubmit = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 1).length
  )
})
const canRatify = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})
const canReview = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 13).length
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => {
      if (allow_purch_application_approval.value == 0) {
        return !(item.status == 2 || item.status == 3)
      } else {
        return !(item.status === 2)
      }
    }).length
  )
})
const canStop = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => {
      if (allow_purch_application_re_approval.value === 0) {
        if (allow_purch_application_approval.value === 0) {
          return !(item.status == 5)
        } else {
          return !(item.status == 5 || item.status == 3)
        }
      } else {
        return !(item.status == 5 || item.status == 3)
      }
    }).length
  )
})
const canMerge = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter(
      (item) =>
        item.status !== 1 &&
        item.status !== 2 &&
        item.status !== 3 &&
        item.status !== 13
    ).length
  )
})

let obj = {
  mergeTypeValue: {
    label: '合并状态',
    value: 'mergeTypeValue',
    asValue: 'mergeType',
    componentType: 'select-model',
    code: 'merge_type',
    show: false,
    hidden: true,
  },
  beforeMergeStatusValue: {
    label: '合并前状态值',
    value: 'beforeMergeStatusValue',
    asValue: 'beforeMergeStatus',
    componentType: 'select-model',
    code: 'purch_application_status',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'purch_application_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function _search() {
  search()
}
function _advancedSearchShow() {
  advancedSearchShow()
}
function _clearSearch() {
  clearSearch()
}
const clearType = ref(true)
const slipSelectRequest = ref(true)
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function ifRenderStop(row) {
  return (
    row.status === 5 ||
    (row.status === 3 &&
      proxy.$store.state.permission.systemConfig
        .allow_purch_application_approval === 1) ||
    (row.status === 3 &&
      proxy.$store.state.permission.systemConfig
        .allow_purch_application_approval === 1 &&
      proxy.$store.state.permission.systemConfig
        .allow_purch_application_re_approval === 1)
  )
}
function ifRenderRevoke(row) {
  return (
    row.status === 2 ||
    (row.status === 3 &&
      proxy.$store.state.permission.systemConfig
        .allow_purch_application_approval != 1)
  )
}
function returnModify() {
  if (modifyInfo.orderId) {
    getList()
  } else {
    search()
  }
}
function closeDialog() {
  pageDialogInfo.value.visible = false
  pageFormInfo.value.data = {}
}
function handelGeneratePurch(row) {
  if (
    proxy.$store.state.permission.systemConfig.purch_according != '1' &&
    proxy.$store.state.permission.systemConfig.purch_according != '2'
  ) {
    pageDialogInfo.value.visible = true
    selectRow.value = row
  } else {
    const params = {
      isDefault: '1',
    }
    const validateApi = applicationsValidatePurch
    validateApi(row).then((resp) => {
      if (resp && resp.success) {
        getReceiveAddressAll(params).then((resp) => {
          if (resp && resp.success) {
            sessionStorage.setItem('storeRowId', row.id)
            purchOrderCheckApplicationInfo.value.visible = true
            purchOrderCheckApplicationInfo.value.orderId = row.id
            purchOrderCheckApplicationInfo.value.info = row
            purchOrderCheckApplicationInfo.value.purchAccording =
              proxy.$store.state.permission.systemConfig.purch_according
          }
        })
      }
    })
    return
  }
}
function saveDialog() {
  if (pageFormInfo.value.data.purch_according) {
    const params = {
      isDefault: '1',
    }
    const validateApi = applicationsValidatePurch
    validateApi(selectRow.value).then((resp) => {
      if (resp && resp.success) {
        getReceiveAddressAll(params).then((resp) => {
          if (resp && resp.success) {
            sessionStorage.setItem('storeRowId', selectRow.value.id)
            purchOrderCheckApplicationInfo.value.orderId = selectRow.value.id
            purchOrderCheckApplicationInfo.value.info = selectRow.value
            purchOrderCheckApplicationInfo.value.purchAccording =
              pageFormInfo.value.data.purch_according
            closeDialog()
            proxy.$nextTick(() => {
              purchOrderCheckApplicationInfo.value.visible = true
            })
          }
        })
      }
    })
    return
  } else {
    proxy.$message.warning('请选择采购依据')
  }
}
// 创建
function create() {
  modifyInfo.visible = true
  modifyInfo.title = '新增申购单'
  modifyInfo.orderId = ''
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.visible = true
  modifyInfo.title = '修改申购单'
  modifyInfo.orderId = data.id
}
function close() {
  proxy.dialogInfo.visible = false
  proxy.formInfo.data = {}
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.visible = true
  detailInfo.data = { ...row }
}
function remove(row) {
  removePurchApplication([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = [
    {
      fieldName: 'deptId',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
    {
      asTbName: 'purch_application',
      columnName: 'purch_product_type',
      queryType: 'EQUALS',
      queryResource: 0,
      queryCategory: 'AND',
      value: '1',
    },
  ]
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}

function handelMethodRequest(row = undefined, method) {
  const ids = getSelectionIds(row)
  if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: row.id,
          rejectReason: value,
        }
        methodPurchApplication(data, method).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  } else if (method === 'return') {
    proxy
      .$prompt('请输入退回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.isNotEmptyString,
        inputErrorMessage: '请输入退回理由并不超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: row.id,
          returnReason: value,
        }
        methodPurchApplication(data, method).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  } else if (method === 'stop') {
    proxy
      .$confirm('中止后单据将变为已中止状态，是否继续中止？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        methodPurchApplication(ids, method).then((resp) => {
          if (resp.success) {
            tableInfo.refresh = Math.random()
          }
        })
      })
  } else if(method === 'submit'){
    applicationsSubmitValidatePlanRemind(ids).then(res => {
      if(res && res.success){
        methodPurchApplication(ids, method).then((resp) => {
          if (resp.success) {
            tableInfo.refresh = Math.random()
          }
        })
      }
    })
  } else {
    methodPurchApplication(ids, method).then((resp) => {
      if (resp.success) {
        tableInfo.refresh = Math.random()
      }
    })
  }
}
function getSelectionIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map(function (item) {
      return item.id
    })
  }
  return ids
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...filterInfo.query.queryMap,
        ...searchInfo.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = postPurchApplicationPage
      getList()
    }
  })
}
</script>

<style scoped></style>
